package com.auditlog.sql.wrapper;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitor;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.PlainSelect;

public class JoinDeParser {

    public String deParse(Join join, ExpressionVisitor expressionVisitor, StringBuilder builder) {
        if (join.isSimple() && join.isOuter()) {
            builder.append("OUTER ").append(join.getRightItem());
        } else if (join.isSimple()) {
            builder.append(join.getRightItem());
        } else {
            if (join.isRight()) {
                builder.append("RIGHT ");
            } else if (join.isNatural()) {
                builder.append("NATURAL ");
            } else if (join.isFull()) {
                builder.append("FULL ");
            } else if (join.isLeft()) {
                builder.append("LEFT ");
            } else if (join.isCross()) {
                builder.append("CROSS ");
            }

            if (join.isOuter()) {
                builder.append("OUTER ");
            } else if (join.isInner()) {
                builder.append("INNER ");
            } else if (join.isSemi()) {
                builder.append("SEMI ");
            }

            if (join.isStraight()) {
                builder.append("STRAIGHT_JOIN ");
            } else if (join.isApply()) {
                builder.append("APPLY ");
            } else {
                builder.append("JOIN ");
            }

            builder.append(join.getRightItem()).append((join.getJoinWindow() != null) ? " WITHIN " + join.getJoinWindow() : "");
        }

        for (Expression onExpression : join.getOnExpressions()) {
            builder.append(" ON ");
            onExpression.accept(expressionVisitor);
        }
        if (join.getUsingColumns().size() > 0) {
            builder.append(PlainSelect.getFormatedList(join.getUsingColumns(), "USING", true, true));
        }

        return builder.toString();
    }

}
